import IntegrationTable, {
	IntegrationTableProps,
} from "@/components/IntegrationTable";
import { ProColumns } from "@ant-design/pro-table";
import React, { useEffect, useRef } from "react";
import { DynamicFormItem } from "@/components/DynamicForm";
import { Image, Radio, Popconfirm, message, Tag, Button, Card } from "antd";
import { arrayToObject, getArray, getString } from "phinney-toolkit";
import { updateStatus } from "./service";
import { PaperClipOutlined } from "@ant-design/icons";
import QRCode from "qrcode-react";
import { divide } from "lodash";
import copy from "copy-to-clipboard";

// @page 商家
const Appversions: React.FC<any> = () => {
	// 组件是否已经卸载
	let isUnMounted = false;
	const actionRef = useRef<any>();
	const textAreaRef = useRef("");

	// 状态列表
	const updateModelList = [
		{ label: "IOS", value: "ios" },
		{ label: "Android", value: "android" },
	];

	const canCancelList = [
		{ label: "否", value: "0" },
		{ label: "是", value: "1" },
	];

	// 状态列表
	const updateTemplate = [
		{ label: "模板1", value: "1" },
		{ label: "模板2", value: "2" },
		{ label: "模板3", value: "3" },
		{ label: "模板4", value: "4" },
		{ label: "模板5", value: "5" },
	];

	// DEBUG版本
	const debugList = [
		{ label: "排除", value: "0", msg: "DEBUG版本无法收到此更新包" },
		{ label: "包含", value: "1", msg: "DEBUG版本可以收到此更新包" },
		{
			label: "仅DEBUG",
			value: "2",
			msg: "只有DEBUG版本可以收到此更新包(一般用于测试)。",
		},
	];
	//强制更新列表
	const forceUpdate = [
		{
			label: "自由更新",
			value: "0",
			msg: "自由更新：显示【以后再说】关闭提示按钮。",
		},
		{
			label: "强制更新",
			value: "1",
			msg: "强制更新：隐藏【以后再说】关闭提示按钮。",
		},
	];

	const statusType = [
		{ label: "启用", value: 1 },
		{ label: "禁用", value: 2 },
	];

	//ossurl
	const ossImageUrl: any = [
		{
			url: "http://see-tech.oss-cn-hangzhou.aliyuncs.com/resource/oss1.png",
			value: 1,
		},
		{
			url: "http://see-tech.oss-cn-hangzhou.aliyuncs.com/resource/oss2.png",
			value: 2,
		},
		{
			url: "http://see-tech.oss-cn-hangzhou.aliyuncs.com/resource/oss3.png",
			value: 3,
		},
		{
			url: "http://see-tech.oss-cn-hangzhou.aliyuncs.com/resource/oss4.png",
			value: 4,
		},
		{
			url: "http://see-tech.oss-cn-hangzhou.aliyuncs.com/resource/oss5.png",
			value: 5,
		},
	];

	/**
	 * 更新
	 *
	 * @param values
	 *
	 */
	const hadnleUpdateStatus = async (values: any, status: any) => {
		console.log(values);
		try {
			const res = await updateStatus({ id: values, status });
			if (res?.code === 200) {
				message.success(res.msg || "");
				actionRef.current?.reload();
			} else {
				message.error(res.msg || "");
			}
			return true;
		} catch (error) {
			message.error("操作失败请重试！");
			return false;
		}
	};

	// 表格项
	const columns: ProColumns[] = [
		{
			title: "日期",
			dataIndex: "time",
			valueType: "dateRange",
			hideInTable: true,
			search: {
				transform: (value: any) => ({
					startTime: value[0],
					endTime: value[1],
				}),
			},
		},
		// {
		// 	title: "版本",
		// 	dataIndex: "version",
		// 	search: false,
		// 	render: (_, record: any) => {
		// 		return (
		// 			<div>
		// 				<Tag icon={<PaperClipOutlined />} color="blue">
		// 					{record.version}
		// 				</Tag>
		// 			</div>
		// 		);
		// 	},
		// },
		{
			title: "更新时间",
			dataIndex: "updateTime",
			search: false,
			render: (_, record: any) => {
				return (
					<>
						<Tag color="blue">{record.updateTime}</Tag>
					</>
				);
			},
		},
		{
			title: "IOS下载地址",
			dataIndex: "iosUrl",
			search: false,
			render: (_, record: any) => {
				return (
					<>
						<div
							style={{
								marginBottom: "10" + "px",
								marginLeft: "10" + "px",
								fontSize: "14" + "px",
							}}
						>
							请使用微信扫码
						</div>
						<QRCode value={record?.iosUrl} />
					</>
				);
			},
		},
		{
			title: "android下载地址",
			dataIndex: "androidUrl",
			search: false,
			render: (_, record: any) => {
				return (
					<>
						<div
							style={{
								marginBottom: "10" + "px",
								fontSize: "14" + "px",
							}}
						>
							请使用自带浏览器扫码
						</div>
						<QRCode value={record?.androidUrl} />
					</>
				);
			},
		},
		{
			title: "平台",
			dataIndex: "platform",
			search: false,
		},
		{
			title: "更新模板",
			dataIndex: "templateId",
			search: false,
			render: (_, record: any) => {
				return (
					<Image
						src={ossImageUrl[record.templateId]?.url}
						style={{ padding: 8 }}
						width={120}
						alt=""
					/>
				);
			},
		},
		{
			title: "是否强制",
			dataIndex: "forced",
			search: false,
			render: (_, record: any) => {
				return record?.status === 1 ? (
					<Tag color="blue">强制更新</Tag>
				) : (
					<Tag color="blue">自由更新</Tag>
				);
			},
		},
		{
			title: "debug",
			dataIndex: "forced",
			search: false,
			render: (_, record: any) => {
				return record?.status === 1 ? (
					<Tag color="blue">包含Debug</Tag>
				) : record?.status === 0 ? (
					<Tag color="blue">排除Debug</Tag>
				) : (
					<Tag color="blue">仅Debug</Tag>
				);
			},
		},

		{
			title: "状态",
			dataIndex: "status",
			search: false,
			render: (_, record: any) => {
				return record?.status === 1 ? (
					<div>
						<Popconfirm
							title="确定禁用吗?"
							onConfirm={() => {
								hadnleUpdateStatus(record.id, 2);
							}}
							okText="确定"
							cancelText="取消"
						>
							<Button type="primary" danger size="small">
								禁用
							</Button>
						</Popconfirm>
					</div>
				) : record?.status === 2 ? (
					<div>
						<Popconfirm
							title="确定启用吗?"
							onConfirm={() => {
								hadnleUpdateStatus(record.id, 1);
							}}
							okText="确定"
							cancelText="取消"
						>
							<Button type="primary" size="small">
								启用
							</Button>
						</Popconfirm>
					</div>
				) : (
					<div>
						{" "}
						<Tag color="red">已删除</Tag>
					</div>
				);
			},
		},
	];

	const getFormItems = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		const { coupon } = vm.state;
		return [
			{
				type: "text",
				label: "Tag名称，版本名称",
				name: "tagName",
				required: true,
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							大版本号规范：xx.xx.xx,热更新版本号:xx.xx.xx,热更新版本不发版
						</span>
					);
				},
			},
			{
				type: "text",
				label: "版本更新标题",
				name: "title",
				required: true,
			},
			{
				type: "textarea",
				label: "版本号",
				name: "version",
				required: true,
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							要更新的版本号：iOS为Build编译版本号，安卓为versionCode应用版本号
						</span>
					);
				},
			},
			{
				type: "textarea",
				label: "版本更新内容",
				name: "content",
				required: true,
			},

			{
				type: "select",
				name: "platform",
				label: "更新平台",
				required: true,
				options: updateModelList,
				fieldProps: {
					mode: "multiple",
				},
			},
			{
				type: "custom",
				name: "templateId",
				required: true,
				label: "更新模板",
				render: (form: any, record: any) => {
					return (
						<div>
							<div>
								<Radio.Group
									options={updateTemplate}
									defaultValue={record?.templateId}
									onChange={({ target }) => {
										form?.setFieldsValue({ templateId: target?.value });
									}}
								></Radio.Group>
							</div>
							<div>
								{ossImageUrl.map((item: any) => {
									return (
										<Image
											src={item.url}
											style={{ padding: 8 }}
											width={90}
											alt=""
										/>
									);
								})}
							</div>
						</div>
					);
				},
			},
			{
				type: "custom",
				name: "debug",
				required: true,
				label: "DEBUG版本",
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={debugList}
							defaultValue={record?.debug}
							onChange={({ target }) => {
								form?.setFieldsValue({ debug: target?.value });
								vm.setState({
									debugMsg: debugList[target?.value].msg,
								});
							}}
						></Radio.Group>
					);
				},
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							{vm.state.debugMsg}
						</span>
					);
				},
			},
			{
				type: "text",
				label: "IOSUrl",
				name: "iosUrl",
				required: true,
			},
			{
				type: "text",
				label: "androidUrl",
				name: "androidUrl",
				required: true,
			},
			{
				type: "custom",
				name: "forced",
				label: "强制更新",
				required: true,
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={forceUpdate}
							defaultValue={record?.forced}
							onChange={({ target }) => {
								form?.setFieldsValue({ forced: target?.value });
								vm.setState({
									forcedMsg: forceUpdate[target?.value].msg,
								});
							}}
						></Radio.Group>
					);
				},
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							{vm.state.forcedMsg}
						</span>
					);
				},
			},
			{
				type: "custom",
				label: "是否允许取消更新",
				name: "canCancel",
				required: true,
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={canCancelList}
							defaultValue={record?.canCancel}
							onChange={({ target }) => {
								form?.setFieldsValue({ canCancel: target?.value });
							}}
						></Radio.Group>
					);
				},
			},
			{
				type: "custom",
				label: "status",
				name: "status",
				required: true,
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={statusType}
							defaultValue={record?.status}
							onChange={({ target }) => {
								form?.setFieldsValue({ status: target?.value });
							}}
						></Radio.Group>
					);
				},
			},
		];
	};

	// 一体化表格props
	const tablePorps: IntegrationTableProps = {
		rowKey: "id",
		scroll: { x: 1000 },
		columns,
		actionRef,
		listProps: {
			url: "/version/update-list",
			method: "GET",
			requestType: "params",
			paramsHandle: (params: any) => {
				return {
					...params,
				};
			},
			modalProps: {
				formProps: {
					labelCol: { span: 8 },
				},
			},
		},
		addProps: {
			url: "/version/update-add",
			method: "POST",
			modalProps: {
				width: 700,
				formProps: {
					labelCol: { span: 6 },
				},
				formItemsHandle: (_: any, vm: any) => {
					return getFormItems(vm);
				},
				formValuesHandle: (record: any) => {
					const roleNames = getString(record?.platform).split(",");
					const roleMap = arrayToObject(updateModelList, {
						label: "value",
						value: "label",
					});

					return {
						...record,
						platform: roleNames.map((m) => roleMap[m]).filter(Boolean),
						forced: !record.forced ? "0" : record.forced,
						debug: !record.debug ? "1" : record.debug,
						templateId: !record.templateId ? "1" : record.templateId,
						canCancel: !record.canCancel ? "0" : record.canCancel,
						status: !record.status ? 1 : record.status,
					};
				},
				content: {
					onInit: (vm) => {
						vm.setState({
							debugMsg: "DEBUG版本无法收到此更新包。",
							forcedMsg: "自由更新：显示【以后再说】关闭提示按钮。",
						});
					},
				},
			},
			paramsHandle: (params: any) => {
				return {
					...params,
					androidMode: "dd",
					// status: "2",
					platform: getArray(params.platform).toString(),
				};
			},
		},
		handleOperating: () => {
			return [
				{
					type: "modal",
					props: {
						url: "/version/update-edit",
						method: "POST",
						btnText: "编辑",
						modalProps: {
							width: 700,
							formProps: {
								labelCol: { span: 6 },
							},
							title: "编辑",
							formItemsHandle: (_: any, vm: any) => {
								return getFormItems(vm);
							},
							formValuesHandle: ({ platform, ...params }) => {
								return {
									platform: platform.split(","),
									...params,
								};
							},
							content: {
								onInit: (vm) => {
									vm.setState({
										debugMsg: debugList[vm.state?.record?.debug].msg,
										forcedMsg: forceUpdate[vm.state?.record?.forced].msg,
									});
								},
							},
						},
						paramsHandle: (params: any, record: any) => ({
							...params,
							id: record.id,
							platform: getArray(record.platform).toString(),
						}),
					},
				},
				{
					type: "custom",
					props: {
						btnText: "复制版本号",
						btnClick: (record: any) => {
							if (copy(record.version)) {
								message.success("复制成功!");
							}
						},
					},
				},
			];
		},
	};

	// 初始化加载数据
	useEffect(() => {
		return () => {
			isUnMounted = true;
		};
	}, []);
	return <IntegrationTable {...tablePorps} />;
};

export default Appversions;
